package com.itheima.aspect;

import com.itheima.domain.po.OperateLog;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private HttpServletRequest request;

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.annotation.Log)")
    public Object Log(ProceedingJoinPoint pjp) throws Throwable {
        log.info("开始执行方法");
        Long start = System.currentTimeMillis(); //开始时间
        //获取日志信息
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        //获取操作员工ID
        Integer operateEmpId = (Integer) claims.get("id");
        //获取当前操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //获取操作类名
        String className = pjp.getTarget().getClass().getName();
        //获取操作方法名
        String methodName = pjp.getSignature().getName();
        //获取操作方法参数
        String methodParams = Arrays.toString(pjp.getArgs());
        //获取操作返回值
        Object result = pjp.proceed();
        String returnValue = result.toString();
        //获取操作耗时
        Long end = System.currentTimeMillis();
        Long costTime = end - start;
        //封装数据到OperateLog中
        OperateLog log = new OperateLog(null, operateEmpId, operateTime, className, methodName, methodParams, returnValue, costTime,null);
        //调用Mapper层方法插入日志
        operateLogMapper.insertOperateLog(log);

        return  result;
    }
}